import CryptoJS from 'crypto-js/crypto-js';
import {useRouterParams} from '@/store/routerParams';
import { ElNotification,ElMessageBox } from 'element-plus'
// import pinia from '@/store/asPinia'
const routerParams = useRouterParams();
//计算两个日期相差天数
export function timecompare(date1, date2) {
  var sdate = new Date(date1);
  var now = new Date(date2);
  var days = now.getTime() - sdate.getTime();
  var day = parseInt(days / (1000 * 60 * 60 * 24));
  return parseInt(day);

}
export function optionsFormat(data, format) {
  var returnData = []
  for (let index = 0; index < data.length; index++) {
    returnData.push({
      value: data[index][format.value],
      label: data[index][format.label]
    })
  }
  return returnData
}
export function stringToDate(strDate) {
  var st = strDate;
  var a = st.split(" ");
  var b = a[0].split("-");
  var c = a[1].split(":");
  var date = new Date(b[0], b[1], b[2], c[0], c[1], c[2]);
  return date;
}
export function dateFormat(date, fmt) {
  let ret;
  const opt = {
    "y+": date.getFullYear().toString(), // 年
    "M+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "h+": date.getHours().toString(), // 时
    "m+": date.getMinutes().toString(), // 分
    "s+": date.getSeconds().toString() // 秒
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
      );
    }
  }
  return fmt;
}
export function fomatDate(date) { //时间转换
  if(!date)return
  let anydate = new Date(date);
  let year = anydate.getFullYear();
  let month = anydate.getMonth() + 1;
  let day = anydate.getDate();
  if (month < 10) {
    month = '0' + month
  }
  if (day < 10) {
    day = '0' + day
  }
  let anytime = year + '-' + month + '-' + day
  return anytime
}


export function formatDate(val) {
  if (val != null) {
    var date = new Date(parseInt(val, 10) * 1000);//如果是13位的时间戳，这里不用*1000
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    var dateStr = date.getFullYear() + "-" + month + "-" + currentDate + " " + hour + ":" + minute + ":" + second;
    return dateStr
  }
}
/*
 * 导出excel
 * @param { Array } params.excelHeader 导出excel的表头 例：['类型', '合同号', '账户名', '币种', '金额']
 * @param { Array } params.excelFilterVal 导出数据所需的字段(multipleSelection或defaultList对象的属性) 例：['type', 'contractCode', 'accountName', 'currency', 'amount']
 * @param { Array } params.multipleSelection 导出勾选的单笔或多笔数据
 * @param { Array } params.defaultList 默认导出列表所有数据
 * @param { Array } params.fileName 导出excel的文件名
 */
export function exportExcel(params) {
  let excelHeader = params.excelHeader
  let excelFilterVal = params.excelFilterVal
  if (params.page) {
    require.ensure([], () => {
      let {
        export_json_to_excel2
      } = require('@/components/Excel/Export2Excel'); //默认为导出全部列表，也可以单笔导出或勾选多笔批量导出
      let formatData = []
      let listArr = params.multipleSelection.length > 0 ? JSON.parse(JSON.stringify(params.multipleSelection)) : JSON.parse(JSON.stringify(params.defaultList));
      params.multipleSelection.forEach((item, index) => {
        // console.log(params.multipleSelection)
        // if(item.sheetData){
        // console.log(item)
        formatData.push({ "data": formatJson(excelFilterVal, item.sheetData), "sheetName": item.sheetName })
        // }
      })
      // let formatData = formatJson(excelFilterVal, listArr);

      function formatJson(excelFilterVal, listArr) {
        return listArr.map(v => {
          return excelFilterVal.map(j => v[j]);
        })
      }
      // console.log(excelHeader,"excelHeader")
      export_json_to_excel2(excelHeader, formatData, params.fileName);
    })
  } else {
    require.ensure([], () => {
      let {
        export_json_to_excel
      } = require('@/components/Excel/Export2Excel'); //默认为导出全部列表，也可以单笔导出或勾选多笔批量导出
      let listArr = params.multipleSelection.length > 0 ? JSON.parse(JSON.stringify(params.multipleSelection)) :
        JSON.parse(JSON.stringify(params.defaultList));
      let formatData = formatJson(excelFilterVal, listArr);

      function formatJson(excelFilterVal, listArr) {
        return listArr.map(v => {
          return excelFilterVal.map(j => v[j]);
        })
      }
      export_json_to_excel(excelHeader, formatData, params.fileName);
    })
  }
}
//小数位
export function getDecimals() {
  return 2
}
//取消千分位
export function replaceFormat(value) {
  if (value == null || value == undefined) {
    return 0.00
  }
  return value.toString().replace(/,/g, "")
}
//添加千分位
export function moneyFormat(value, wei) {
  let num = ""
  if (wei) {
    num = wei
  } else {
    num = 2
  }
  if (value == null || value == undefined) {
    return 0.00
  }
  return parseFloat(value).toFixed(num).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}

//arrlist 接口获取list数据
//tableColumn 根据那一列参数小计，列的参数key值 eg：'deptFloorCode'
//sumColumn 要合计的列的参数组成的数组 eg：['sumTicketSale','netSale','noTaxMoney','outTaxMoney']
//minColumn 要显示小计两个字那一列参数 eg：'shopNo'
//arr 计算类似于扣率的值 eg：[['taxRate','sumTicketSale','netSale']]
export function minSum(arrlist, tableColumn, sumColumn, minColumn, arr) { //小计合计方法
  let obj = {};
  let newArray = [];
  for (let i = 0; i < arrlist.length; i++) {

    if (i == 0) {
      newArray.push(arrlist[i])
      for (let j = 0; j < sumColumn.length; j++) {
        obj[sumColumn[j]] = 0;
        obj[sumColumn[j]] = Number(obj[sumColumn[j]]) + Number(arrlist[i][sumColumn[j]]);
      }
      if (arr) {
        for (let m = 0; m < arr.length; m++) {
          obj[arr[m][0]] = this.twoFilex(Number(obj[arr[m][1]]) / Number(obj[arr[m][2]]))
        }
      }
    } else if (i > 0) {

      if (arrlist[i][tableColumn] != arrlist[i - 1][tableColumn]) {
        obj[minColumn] = '小计：';
        newArray.push(JSON.parse(JSON.stringify(obj)));
        for (let j = 0; j < sumColumn.length; j++) {
          obj[sumColumn[j]] = 0;
          obj[sumColumn[j]] = this.twoFilex(Number(obj[sumColumn[j]]) + Number(arrlist[i][sumColumn[j]]));
        }
        if (arr) {
          for (let m = 0; m < arr.length; m++) {
            obj[arr[m][0]] = this.twoFilex(Number(obj[arr[m][1]]) / Number(obj[arr[m][2]]))
          }
        }
        newArray.push(arrlist[i])

        if (i == arrlist.length - 1) {
          obj[minColumn] = '小计：';
          newArray.push(JSON.parse(JSON.stringify(obj)));
        }
      } else {

        for (let j = 0; j < sumColumn.length; j++) {
          obj[sumColumn[j]] = this.twoFilex(Number(obj[sumColumn[j]]) + Number(arrlist[i][sumColumn[j]]));
        }

        if (arr) {
          for (let m = 0; m < arr.length; i++) {
            obj[arr[m][0]] = this.twoFilex(Number(obj[arr[m][1]]) / Number(obj[arr[m][2]]))
          }
        }

        newArray.push(arrlist[i])
        if (i == arrlist.length - 1) {
          obj[minColumn] = '小计：';
          newArray.push(JSON.parse(JSON.stringify(obj)));
        }
      }

    }

  }
  for (let k = 0; k < newArray.length - 1; k++) {
    if (newArray[k][minColumn] == '小计：') {
      for (let j = 0; j < sumColumn.length; j++) {

        obj[sumColumn[j]] = this.twoFilex(Number(obj[sumColumn[j]]) + Number(newArray[k][sumColumn[j]]));

      }
    }
  }
  obj[minColumn] = '合计：';
  newArray.push(JSON.parse(JSON.stringify(obj)));
  // angular.forEach(newArray, function (item) {
  //   if (item[minColumn] == '小计：' || item[minColumn] == '合计：') {
  //     item.size = 700
  //   }
  // })
  arrlist = newArray;
  return arrlist
}



// 默认的 KEY 与 iv 如果没有给
const KEY = CryptoJS.enc.Utf8.parse("_aes_secret_key_");
const IV = CryptoJS.enc.Utf8.parse('_aes_secret_iv__');

/**
 * AES加密 ：字符串 key iv  返回base64
 */
export function Encrypt(word, keyStr, ivStr) {
  let key = KEY
  let iv = IV

  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }

  let srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
  });
  // console.log("-=-=-=-", encrypted.ciphertext)
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);

}

/**
 * AES 解密 ：字符串 key iv  返回base64
 *
 */
export function Decrypt(word, keyStr, ivStr) {
  let key = KEY
  let iv = IV

  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }

  let base64 = CryptoJS.enc.Base64.parse(word);
  let src = CryptoJS.enc.Base64.stringify(base64);

  var decrypt = CryptoJS.AES.decrypt(src, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
  });

  var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}

export function groupBy(key, array) {
  const result = {}
  array.forEach((item) => {
    if (result[item[key]]) {
      result[item[key]].push(item)
    } else {
      result[item[key]] = [item]
    }
  })
  // console.log(result)
  return result
}
export function objAssign(base, obj) {
  for (const key in obj) {
    base[key] = obj[key];
  }
}

export function deepClone(obj, createWebHashHistory) {
  if (!hash) hash = new WeakMap()
  // 不是对象（普通值类型/function）,null,undefined,正则，Date都会直接返回
  if (obj == null || typeof obj != 'object') {
    return obj
  }
  if (obj instanceof RegExp) {
    return new RegExp(obj)
  }
  if (obj instanceof Date) {
    return new Date(obj)

  }

  // 判断是否循环引用的（判断属性是不是存在了）
  if (hash.get(obj)) return hash.get(obj)
  let cloneObj;
  if ((obj instanceof HTMLElement)) cloneObj = obj;
  else cloneObj = (obj != undefined && obj.constructor) ? new obj.constructor() : {};


  // 存obj
  hash.set(obj, cloneObj)

  for (let key in obj) {
    // in 循环会遍历原型链的，所以需要判断是否是当前对象的属性
    if (obj.hasOwnProperty && obj.hasOwnProperty(key)) {
      cloneObj[key] = window.deepClone(obj[key], hash)
    }
  }

  return cloneObj
}
export function go(router,path,params){
  routerParams.routerParam[path] = {params}
  router.push(path)
}
export function createFromJson(tableHead){
  const result = []
  tableHead.forEach((head)=>{
    const obj = {}
    obj.label = head.name;
    obj.value = head.field;
    obj.type = "input"
    obj.placeholder =  head.name;
    obj.show = head.show;
    obj.rule = {required: false}


    result.push(obj)
  })
  console.log(JSON.stringify(result));
  
  return result
}

export function message(message,type){
  ElNotification({ message, type: type ? type:'info' })
}

export function MessageBox(value,Fn){
  if(!value)value = '确定删除吗'
  ElMessageBox.confirm(value, '', {
    distinguishCancelAndClose: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(Fn).catch(() => {})
}

